<template>
  <div class="roleManage">
    <my-header
      class="roleManage__header"
      :leftText="headerInfo.leftText"
      :title="headerInfo.title"
    ></my-header>

    <div class="roleManage__content">
      <van-swipe-cell v-for="(item, index) in roleList" :key="index">
        <van-cell :value="item.roleName" />
        <template #right>
          <van-button square type="danger" text="删除" @click="deleteRole(item, index)" />
        </template>
      </van-swipe-cell>

      <van-button class="btn-add" type="info" block @click="showPickerRole = true">添加</van-button>

      <!-- 用户角色选择器 -->
      <van-popup v-model="showPickerRole" round position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          @cancel="showPickerRole = false"
          @confirm="addRole"
        />
      </van-popup>
    </div>
  </div>
</template>

<script>
import { Notify } from "vant";
import { queryAllRoles } from "@/api/role";
import { queryAllUserRoles, addUserRole, delUserRole } from "@/api/userInfo";
import MyHeader from "@/components/Header";

export default {
  name: "userRoleManage",
  components: {
    MyHeader
  },
  data() {
    return {
      userId: this.$route.params.id || "",
      headerInfo: {
        leftText: "返回",
        title: "角色管理"
      },
      showPickerRole: false,
      roleList: [],
      rolePicker: [],
      columns: []
    };
  },
  created() {
    this.getRolesPicker();
    this.getUserRoleList();
  },
  methods: {
    // 获取所有角色列表
    getRolesPicker() {
      queryAllRoles({
        page: 1,
        pageSize: 100,
        filters: {},
        sorts: null
      }).then((el = []) => {
        console.info(el)
        this.rolePicker = el.list;
        this.rolePicker.forEach(item => {
          this.columns.push(item.roleName);
        });
      });
    },
    // 获取用户角色列表
    getUserRoleList() {
      queryAllUserRoles(this.userId).then((el = []) => {
        this.roleList = el;
      });
    },
    // 添加用户角色
    addRole(value) {
      let haveValue = this.roleList.filter(el => {
        return el.roleName === value;
      });
      if (haveValue.length === 0) {
        // 添加用户角色
        let roleId;
        this.rolePicker.map(el => {
          if (el.roleName === value) {
            roleId = el.id;
          }
        });
        addUserRole([
          {
            userId: this.userId,
            roleId
          }
        ]).then(el => {
          this.roleList.push({ roleName: value });
          this.showPickerRole = false;
        });
      } else {
        Notify({ type: "danger", message: `该用户已存在${value}角色` });
      }
    },
    // 删除用户角色
    deleteRole(key, index) {
      delUserRole({
        userId: this.userId,
        roleId: key.id
      }).then(el => {
        this.roleList.splice(index, 1);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.roleManage {
  &__content {
    margin-top: 20px;
    .btn-add {
      margin-top: 20px;
    }
  }
}
</style>
